/**
 *
 */
package com.hz.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;

import com.hz.model.User;
import com.hz.services.UserServices;
import com.hz.services.impl.UserServicesImpl;

/**
 * @author Administrator
 * @date 2018年6月20日 下午8:21:46
 * 
 */
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
	
	private UserServices userSerices = new UserServicesImpl();
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		User user = getParameterFromRequest(req);
//		PrintWriter print = resp.getWriter();
		String result = "";
		if(user.getName() == null || user.getPassword() == null) {
			result = "login failure";
		}else {
			int count = userSerices.login(user);
			if(count > 0) {
				result = "login success";
			}else {
				result = "login failure";
			}
		}
//		print.write(result);
		//页面的跳转
		req.getRequestDispatcher("/WEB-INF/jsp/index.jsp").forward(req, resp);
		
	}
	
	
	private User getParameterFromRequest(HttpServletRequest req) {
		//获取所有参数的对象 map对象
		Map parameters = req.getParameterMap();	
		User user = new User();	
		//把参数的map对象 根据key与对象的属性的对应关系 映射到user实体对象中
		try {
			BeanUtils.populate(user, parameters);
		} catch (IllegalAccessException | InvocationTargetException e) {
			e.printStackTrace();
		}
		return user;
	}
	
}
